package com.yubest.canal;

import com.alibaba.fastjson2.JSON;
import com.alibaba.otter.canal.client.CanalConnector;
import com.alibaba.otter.canal.client.CanalConnectors;
import com.alibaba.otter.canal.protocol.CanalEntry;
import com.alibaba.otter.canal.protocol.Message;
import com.yubest.canal.bean.CanalBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;
import java.util.*;

@Component
@Slf4j
public class CanalListener implements ApplicationRunner {

    @Value("${canal.host: localhost}")
    private String host;

    @Value("${canal.port: 11111}")
    private int port;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        new Thread(this::listener).start();
    }

    private void listener() {
        // 创建链接
        CanalConnector connector = CanalConnectors.newSingleConnector(new InetSocketAddress(host, port),
                "example", "", "");
        int batchSize = 1000;
        try {
            connector.connect();
            //监听canal库下所有表
            connector.subscribe("canal\\..*");
            connector.rollback();
            while (true) {
                // 获取指定数量的数据
                Message message = connector.getWithoutAck(batchSize);
                long batchId = message.getId();
                int size = message.getEntries().size();
                if (batchId == -1 || size == 0) {
                    try {
                        // 获取指定数量的数据
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        log.error("sleep error", e);
                    }
                } else {
                    process(message.getEntries());
                }
                // 提交确认
                connector.ack(batchId);
            }
        } finally {
            connector.disconnect();
        }
    }

    private void process(List<CanalEntry.Entry> entryList) {
        for (CanalEntry.Entry entry : entryList) {
            if (entry.getEntryType() == CanalEntry.EntryType.TRANSACTIONBEGIN
                    || entry.getEntryType() == CanalEntry.EntryType.TRANSACTIONEND) {
                continue;
            }

            CanalEntry.RowChange rowChange = null;
            try {
                rowChange = CanalEntry.RowChange.parseFrom(entry.getStoreValue());
                CanalEntry.EventType eventType = rowChange.getEventType();

                for (CanalEntry.RowData rowData : rowChange.getRowDatasList()) {
                    CanalBean bean = new CanalBean();
                    bean.setType(eventType.name());
                    bean.setSchema(entry.getHeader().getSchemaName());
                    bean.setTable(entry.getHeader().getTableName());

                    Map<String, String> beforeDataMap = new LinkedHashMap<>();
                    for (CanalEntry.Column column : rowData.getBeforeColumnsList()) {
                        beforeDataMap.put(column.getName(), column.getValue());
                    }
                    bean.setBeforeData(beforeDataMap);

                    Map<String, String> afterDataMap = new LinkedHashMap<>();
                    for (CanalEntry.Column column : rowData.getAfterColumnsList()) {
                        afterDataMap.put(column.getName(), column.getValue());
                    }
                    bean.setAfterData(afterDataMap);

                    log.info(JSON.toJSONString(bean));
                }
            } catch (Exception e) {
                log.error(entry.toString());
            }
        }
    }

}
